<template>
    <view
        class="chat-scroll-view"
        :style="{height}"
        id="chatScrollView">

      <view style="position: absolute;z-index:1;width: 100%;height:100%;top:0;left:0;background-color: #fff;"
      v-if="(!list||list.length==0)||!loadFinish">
        <view style="position: absolute;z-index:1;;width: 100%;top:50%;text-align: center;transform: translateY(-50%);">
        <image
            mode="widthFix"
            class="loading-icon-2"
            :src="$kt.file.byPath('icon/chat.svg')"></image>
      </view>

      </view>

      <scroll-view
          :refresher-enabled="refresherEnabled"
          @refresherrefresh="onRefresherrefresh()"
          scroll-y
          class="scroll-view"
          :style="{height}"
          @scroll="onScroll"
          ref="scrollView"
          @scrolltolower="onScrolltolower"
          @scrolltoupper="onScrolltoupper"
          :scroll-into-view="scrollIntoViewId"
      >
        <view>
          <view class="chat-list-container">
<!--            <view-->
<!--                v-if="isBeforeLoading"-->
<!--                class="chat-list-up-loading-box">-->
<!--              <view class="chat-list-up-loading-box-text">{{$i18n.zhToGlobal("加载中")}}</view>-->
<!--            </view>-->
            <view
                :style="{
                textAlign: item.userAccountId == $kt.userAccount.getSelf().id? 'right':'left',
              }"
                v-for="(item,index) in list" :key="index" class="chat-list-item">
              <view :id="getPositionId(item)+''"></view>
              <card-of-user-account
                  :message="item"
              ></card-of-user-account>
            </view>
          </view>
          <view style="height: 20rpx"></view>
          <view :id="scrollIntoViewIdFinal"></view>

        </view>
      </scroll-view>
    </view>
  </template>

<script>

  import CardOfUserAccount from "./conponents/card-of-user-account.vue";

  export default {
    components: {CardOfUserAccount},
    props: {
      height: {
        type: String,
        default: ''
      },
      dialogId: {
        type: Number,
        default: ''
      }
    },
    data() {
      return {
        refresherEnabled:true,
        scrollIntoViewIdFinal: '',
        scrollIntoViewId: 'scrollIntoViewId',
        uuid: null,
        isMoveToEnd: true,

        chatScrollViewHeight: 0,
        chatDialog: {
          id: ''
        },
        list: [],
        loadFinish: false,
        userInfo: {
          fileIdOfAvatar: ''
        },
        maxId: 0,
        minId: 0,
        model: {},
        isBeforeLoading: false,
        // 每次list的长度
        listLength: 20,
        // isTolower,代表是否可以继续加载
        isTolower: true,
        beforePool: [],
      };
    },
    watch: {
      dialogId: {
        handler(val) {
            try{
              this.getInit();
                // 重新渲染
                this.$forceUpdate();
            }catch(e){}
        },
        immediate: true,
        deep: true,
      },
      height: {
        handler(val) {
            try{
                this.getChatScrollViewHeight();
                // 重新渲染
                this.$forceUpdate();
            }catch(e){}
        },
        immediate: true,
        deep: true
      }
    },
    created() {
        // 生成UUID
        this.uuid = this.$kt.util.generateUUID();
        this.initScrollViewId();

        this.$kt.event.on('FunctionalChatDialogMessage:sendMessage', async (data) => {
          if (data.dialogId+"" === this.dialogId+"") {
            console.log("接受到了消息="+JSON.stringify(data))
            // this.list.push(data);
            // 不包含ID的聊天，也就是说不保存在数据库中的数据，先显示出来
            if(!this.isExistMessage(data)&&!data.id) {
              this.list.push({...data,id:0});
            }
            // 保存在数据库中的数据
            if(!this.isExistMessage(data)&&data.id){
              this.pushReal(data);
            }
            this.moveToEnd();
          }
        });

        this.$Kt.event.on('sendMessageSuccess', async (data) => {
          this.list.push({...data,id:0});
        });

      this.$kt.event.on("appShow",async ()=>{
        await this.getAfter();
      });


    },
    mounted() {

    },
    methods: {
      async onRefresherrefresh() {
        if(!this.isTolower){
          this.refresherEnabled = false;
        }
        setTimeout(async () => {
          this.refresherEnabled = false;
          await this.getBefore();
          setTimeout(()=>{
            if(!this.isTolower){
              this.refresherEnabled = false;
              return;
            }
            this.refresherEnabled = true;
          },500);
        }, 1000);
      },
      setScrollIntoViewId(id) {
        this.scrollIntoViewId = ""; // 清空之前的值
        this.$nextTick(() => {
          this.scrollIntoViewId = id; // 确保 DOM 渲染完成后再设置
        });
      },
      onScroll(res) {
        this.isMoveToEnd = false;
        this.$emit('scroll', res);
      },
      onScrolltolower(res) {
        // this.$emit('scrolltolower', res);
        setTimeout(() => {
          this.isMoveToEnd = true;
          console.log(this.isMoveToEnd);
        }, 100);
      },
      onScrolltoupper(res) {
        // this.$emit('scrolltoupper', res);
        // this.getBefore();
      },
      // 移动到最后
      moveToEnd() {
        if (!this.isMoveToEnd) {
          return;
        }
        if (this.loading) {
          return;
        }
        this.scrollIntoViewId = "";
        setTimeout(()=>{
          this.scrollIntoViewId = ""+this.scrollIntoViewIdFinal;
        },1);
        setTimeout(() => {
          this.scrollIntoViewId = ""+this.scrollIntoViewIdFinal;
        }, 100);
      },
      /**
       * 强制移到最底部
       */
      moveToEndForce() {
        this.isMoveToEnd = true;
        this.moveToEnd();
      },
      initScrollViewId() {
        this.uuid = this.$kt.util.generateUUID();
        this.scrollIntoViewIdFinal = 'scrollIntoView_' + this.uuid;
      },
      getPositionId(item){
        return "id_"+item.dialogId+"_"+item.id;
      },
      pushReal(data){
        let virtualId = data.virtualId;
        // 查看有没有重复的虚拟键，有的话先删除
        for(let i = 0; i < this.list.length; i++){
          if(this.list[i].virtualId === virtualId){
            this.list.splice(i,1);
            break;
          }
        }
        this.list.push(data);

      },
      // 往前加
      unshiftBefore(data){
        let virtualId = data.virtualId;
        // 查看有没有重复的虚拟键，有的话先删除
        for(let i = 0; i < this.list.length; i++){
          if(this.list[i].virtualId === virtualId){
            this.list.splice(i,1);
            break;
          }
        }
        this.list.unshift(data);
      },


      isExistMessage(message){
          for(let i = 0; i < this.list.length; i++){
            if(this.list[i].id+"" === message.id+""){
              console.log("消息已存在");
              return true
            }
          }
          console.log("消息不存在");
          return false;
        },
      /**
       * 获取最大和最小ID
       */
        getMaxAndMinId(){
          let maxId = 0;
          let minId = 0;
          for(let i = 0; i < this.list.length; i++){
            if(this.list[i].id > maxId){
              maxId = this.list[i].id;
            }
            if(minId === 0 || this.list[i].id < minId){
              minId = this.list[i].id;
            }
          }
          this.maxId = minId;
          this.minId = maxId;
        },
        async getInit(){
          // /functional-chat-web/dialogMessage/getList
          await this.$request.post('/functional-chat-web/dialogMessage/getList', {
           data:{dialogId: this.dialogId},
          }).then(res => {
            this.list = [];
            if (res.data.length === 0) {
              this.loadFinish = true;
              return;
            }
            // 倒序
            for(let i = res.data.length - 1; i >= 0; i--){
              if(!this.isExistMessage(res.data[i])) {
                this.list.push(res.data[i]);
              }
            }
            this.moveToEndForce();
            setTimeout(()=>{
              this.loadFinish = true;
            },100);
            // 获取最大ID和最小ID
            this.getMaxAndMinId();
          }).catch(err => {
          });
        },
        async getAfter(){
          await this.$request.post('/functional-chat-web/dialogMessage/getList', {
            data:{
              dialogId: this.dialogId,
              minId: this.minId
            }
          }).then(res => {
            console.log("获取到消息",JSON.stringify(res.data));
            if (res.data.length === 0) {
              return;
            }
            console.log("获取到消息",res.data.length);
            // 倒序
            for(let i = res.data.length - 1; i >= 0; i--){
              if(!this.isExistMessage(res.data[i])) {
                this.pushReal(res.data[i]);
              }
            }
            // 获取最大ID和最小ID
            this.getMaxAndMinId();
            try{
              // 重新渲染
              this.$forceUpdate();
            }catch (e) {
            }
            // this.toBottom();
          }).catch(err => {
          });
        },
        async getBefore(){
          if(this.isTolower === false){
            return;
          }
          if(this.isBeforeLoading) {
            return;
          }
          this.isBeforeLoading = true;
          // 如果beforePool中有数据，就直接取5条数据
          if(this.beforePool.length > 0){
            let data = this.beforePool.splice(0,5);
            for(let i = 0; i < data.length; i++){
              this.unshiftBefore(data[i]);
            }
            // 获取最大ID和最小ID
            this.getMaxAndMinId();
            this.isBeforeLoading = false;
            return;
          }

          await this.$request.post('/functional-chat-web/dialogMessage/getList', {
            data:{
              dialogId: this.dialogId,
              maxId: this.maxId
            }
          }).then(async (res) => {
            // 获取当前第一个消息的定位ID
            let firstId = this.getPositionId(this.list[0]);
            console.log("CHAT 第一个消息的定位ID",firstId);
            console.log("获取到消息",JSON.stringify(res.data));
            if(res.data.length < this.listLength){
              this.isTolower = false;
              this.refresherEnabled = false;
              this.isBeforeLoading = false;
              return;
            }
            // if (res.data.length === 0) {
            //   this.isBeforeLoading = false;
            //   return;
            // }
            console.log("获取到消息",res.data.length);
            // 倒序
            for(let i = 0; i < res.data.length; i++){
                  // if(!this.isExistMessage(res.data[i])) {
                  //   this.unshiftBefore(res.data[i]);
                  //   console.log("CHAT 获取到消息2",firstId);
                  // }
              // 取出前5条数据，其余的放入beforePool中
              if(i < 5){
                this.unshiftBefore(res.data[i]);
              }else{
                this.beforePool.push(res.data[i]);
              }
            }
            // setTimeout(()=>{
            //   // 获取res.data.length，如果大于三个，就定位到倒数第三个
            //   if(res.data.length >= 3){
            //     this.setScrollIntoViewId(res.data[res.data.length - 3]);
            //   }
            //   // 如果小于三个，就定位到第一个
            //   if(res.data.length < 3){
            //     this.setScrollIntoViewId(res.data[0]);
            //   }
            //
            // },10)

            // 获取最大ID和最小ID
            this.getMaxAndMinId();
            this.isBeforeLoading = false;
          }).catch(err => {
          });
        },
        // 获取聊天列表的高度
        getChatScrollViewHeight() {

        }
    }
}
</script>

<style lang="scss" scoped>

.chat-scroll-view {
    position: relative;
}

.chat-list-item {
  padding: 20rpx;
  box-sizing: border-box;
}

// 头像
.chat-list-item-avatar {
  vertical-align: top;
  position: relative;

  .chat-list-item-avatar-image {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
  }
}

.chat-list-item-content {
  display: inline-block;
  padding: 20rpx;
  box-sizing: border-box;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  max-width: 700rpx;
}


.chat-list-item-content-img {
  width: 300rpx;
  border-radius: 20rpx;
}

.chat-list-item-content-video {
  width: 450rpx;
  height: 300rpx;
  border-radius: 20rpx;
}

.time-view {
  position: relative;
  font-size: 24rpx;
  color: #999999;

  .copy-icon {
    position: absolute;
    width: 40rpx;
    top: -10rpx;
    right: 0
  }

  .copy-icon:active {
    transform: scale(0.9);
  }
}

.chat-list-item-self {
  text-align: right;
}

.chat-list-item-content-text {
  letter-spacing: 3rpx;
  font-size: 30rpx;
}

.think-box {
  color: #000000;
  font-size: 22rpx;
  top: 45rpx;
}

.loading-icon-2 {
  width: 150rpx;
  height: 150rpx;
}

.chat-list-item-avatar-name {
  position: absolute;
  left: 80rpx;
  top: calc(50% - 10rpx);
  transform: translateY(-50%);
  width: calc(100% - 60rpx);
  font-size: 28rpx;
  color: #666666;
  letter-spacing: 3rpx;
}

.loading-icon-3{
  width: 50rpx;
  height: 50rpx;
  // 颜色反转
  filter: invert(1);
  // 动画
  animation: loading-icon-ani-in-page-chat 3s linear infinite;
}

@keyframes loading-icon-ani-in-page-chat {
  0% {
    transform:  rotate(0deg);
  }
  50% {
    transform:  rotate(720deg);
  }
  100% {
    transform:  rotate(0deg);
  }
}

.chat-list-up-loading-box{
  text-align: center;
  padding: 20rpx;
  box-sizing: border-box;
  .chat-list-up-loading-box-text{
    font-size: 28rpx;
    color: #999999;
  }
}


</style>
